<?php

declare(strict_types = 1);

// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.
// }}}

namespace App\Tests\Entity;

use App\Core\Cache;
use App\Core\DB\DB;
use App\Entity\Actor;
use App\Util\GNUsocialTestCase;
use Component\Circle\Entity\ActorTag;
use Component\Tag\Tag as CompTag;
use Jchook\AssertThrows\AssertThrows;

class ActorTest extends GNUsocialTestCase
{
    use AssertThrows;

    public function testGetAvatarUrl()
    {
        $actor = DB::findOneBy(Actor::class, ['nickname' => 'taken_user']);
        static::assertSame('/avatar/default', $actor->getAvatarUrl());
    }

    public function testSelfTags()
    {
        $actor = DB::findOneBy(Actor::class, ['nickname' => 'taken_user']);
        // Start with no self-tags
        static::assertSame(
            expected: [],
            actual: $actor->getSelfTags(),
        );
        // Add one self-tag 'foo'
        $tag = CompTag::sanitize('foo');
        DB::persist($actor_tag_foo = ActorTag::create([
            'tagger' => $actor->getId(), // self tag means tagger = tagger in ActorTag
            'tagged' => $actor->getId(),
            'tag'    => $tag,
        ]));
        DB::flush();
        Cache::delete(Actor::cacheKeys($actor->getId())['self-tags']);
        $actual = $actor->getSelfTags();
        static::assertCount(1, $actual);
        static::assertObjectEquals(expected: $actor_tag_foo, actual: $actual[0]);
        // Add a second self-tag 'foo'
        $tag = CompTag::sanitize('bar');
        DB::persist($actor_tag_bar = ActorTag::create([
            'tagger' => $actor->getId(), // self tag means tagger = tagger in ActorTag
            'tagged' => $actor->getId(),
            'tag'    => $tag,
        ]));
        DB::flush();
        Cache::delete(Actor::cacheKeys($actor->getId())['self-tags']);
        $actual = $actor->getSelfTags();
        static::assertCount(2, $actual);
        foreach ([$actor_tag_bar, $actor_tag_foo] as $expected) {
            $a = array_shift($actual);
            if ($expected->equals($a) !== true) {
                dd($expected, $a);
            }
            static::assertObjectEquals($expected, $a);
        }
    }
}
